#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <chrono>
#include <memory>
using namespace std;
void yuv4442rgb(unsigned char *RGB, unsigned char *yuv444, int w, int h)
{
    int index = 0;
    for (int y = 0; y < h; ++y)
    {
        for (int x = 0; x < w; ++x)
        {
            // 从 YUV444 数据中提取 Y、U、V 分量
            unsigned char Y = yuv444[index];
            unsigned char U = yuv444[index + w * h];
            unsigned char V = yuv444[index + 2 * w * h];
            // 使用 YUV 转换公式将 YUV 值转换为 RGB 值
            int C = Y - 16;
            int D = U - 128;
            int E = V - 128;
            int R = (298 * C + 409 * E + 128) >> 8;
            int G = (298 * C - 100 * D - 208 * E + 128) >> 8;
            int B = (298 * C + 516 * D + 128) >> 8;
            // 确保 RGB 值在 0 到 255 范围内
            R = (R < 0) ? 0 : ((R > 255) ? 255 : R);
            G = (G < 0) ? 0 : ((G > 255) ? 255 : G);
            B = (B < 0) ? 0 : ((B > 255) ? 255 : B);
            RGB[index * 3] = R;
            RGB[index * 3 + 1] = G;
            RGB[index * 3 + 2] = B;
            index++;
        }
    }
}

int main()
{
    int width = 1920, height = 1080;
    unsigned char *RGB = new unsigned char[width * height * 3];
    unsigned char *yuv444 = new unsigned char[(int)(width * height * 3)];
    FILE *fptr = fopen("screen.yuv444", "rb");
    fread(yuv444, 1, 3 * width * height, fptr);
    fclose(fptr);
    yuv4442rgb(RGB, yuv444, width, height);
    fptr = fopen("screen.yuv4442rgb", "wb");
    fwrite(RGB, 1, 3 * width * height, fptr);
    fclose(fptr);
    delete[] RGB;
    delete[] yuv444;
}